package com.libl.controller;

import com.libl.annotation.RequiresPermissionsDesc;
import com.libl.pojo.DtsRole;
import com.libl.service.DtsPermissionService;
import com.libl.service.DtsRoleService;
import com.libl.util.Permission;
import com.libl.util.PermissionUtil;
import com.libl.util.ResponseUtil;
import com.libl.vo.PermVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/role")
public class DtsAdminRoleController {
    @Autowired
    DtsRoleService roleService;

    @GetMapping("/options")
    public Object options(){
        //查询所有的角色
        List<DtsRole> list = roleService.findAll();
        //数据转换
        List<Map<String, Object>> data = list.stream().map(role -> {
            Map<String, Object> map = new HashMap<>();
            map.put("value", role.getId());
            map.put("label", role.getName());
            return map;
        }).collect(Collectors.toList());

        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:role:list")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"}, button = "角色查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page",required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "limit",required = false, defaultValue = "10") Integer limit ,
            String sort , String order, String rolename
    ) {
        Map<String,Object> data = roleService.queryPage(page, limit, sort, order, rolename);
        //把查询到的数据返回
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:role:create")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"}, button = "角色添加")
    @PostMapping("/create")
    public Object create(@RequestBody DtsRole role){
        roleService.insert(role);
        //把新增后的对象返回
        return ResponseUtil.ok(role);
    }

    // DO: 修改和删除
    @RequiresPermissions("admin:role:update")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"}, button = "角色编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsRole role){
        //修改操作
        roleService.update(role);
        //返回修改后的角色
        return ResponseUtil.ok(role);
    }

    @RequiresPermissions("admin:role:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"}, button = "角色删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsRole role){
        try {
            //删除操作
            roleService.delete(role);
        } catch (Exception e) {
            e.printStackTrace();
            //删除失败
            return ResponseUtil.fail(-1,e.getMessage());
        }
        //删除成功
        return ResponseUtil.ok();
    }


    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    DtsPermissionService permissionService;
    /**
     * 查询树形结构需要的权限信息
     * 数据结构
     *  data:{
     *      systemPermissions: 系统权限（所有权限信息）
     *      assignedPermissions: 当前角色拥有的权限
     *  }
     *
     *  系统权限：解析注解，通过注解配置信息，获取数据
     *  当前角色权限：
     *  1.如果该角色是超级管理员，拥有所有的权限
     *  2.如果不是超级管理员，当前角色权限可以从数据库中查询
     * @param roleId
     * @return
     */
    @GetMapping("/permissions")
    public Object permissions(Integer roleId) {
        //获取系统权限
        List<Permission> permissions = PermissionUtil.listPermission(applicationContext,"com.libl.controller");
        //获取系统权限列表（转换数据结构）
        List<PermVo> systemPermissions = PermissionUtil.listPermVo(permissions);
        //获取当前角色拥有的权限
        Set<String> assignedPermissions;
        //判断角色是否是超级管理员
        if(roleService.isSuperAdmin(roleId)){
            //如果是超级管理员，则拥有所有的权限
            assignedPermissions = PermissionUtil.listPermissionString(permissions);
        }
        else{
            //否则，需要去数据库查询匹配的权限
            assignedPermissions = roleService.queryStringPermissions(roleId);
        }

        Map<String,Object> data = new HashMap<>();
        data.put("systemPermissions",systemPermissions);
        data.put("assignedPermissions",assignedPermissions);

        return ResponseUtil.ok(data);
    }

    //修改授权
    @PostMapping("/permissions")
    public Object permissions(@RequestBody Map<String,Object> map) {
        Integer roleId = (Integer) map.get("roleId");
        ArrayList<String> permissions = (ArrayList<String>) map.get("permissions");
        //如果是超级管理员，则直接返回修改成功
        if(roleService.isSuperAdmin(roleId)){
            return ResponseUtil.ok();
        }
        permissionService.updatePermissions(roleId, permissions);
        return ResponseUtil.ok();
    }

}
